package handler

import (
	"bike-vb/cache"
	"bike-vb/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

// 列表
func GoodOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	/*
		SELECT

		FROM
		  good_orders
		  LEFT JOIN goods ON goods.id = good_orders.gid
	*/
	var list []model.GoodOrderList

	redis_key := "good_order_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").
			Select(
				"good_orders.id as OrderId",
				"goods.good_code as GoodCode",
				"goods.good_name as GoodName",
				"good_orders.order_code as OrderCode",
				"good_orders.order_price as OrderPrice",
			).
			Joins("LEFT JOIN goods ON goods.id = good_orders.gid").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var total int64
	model.DB.Where(&model.GoodOrderList{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "获取成功",
		"data":  list,
		"total": total,
	})
}

// 详情
func GoodOrderDetail(c *gin.Context) {
	id := c.Query("id")
	/*
		SELECT
		  good_orders.id as OrderId,
		  goods.good_code as GoodCode,
		  goods.good_name as GoodName,
		  good_orders.order_code as OrderCOde,
		  good_orders.order_price as OrderPrice
		FROM
		  good_orders
		  LEFT JOIN goods ON goods.id = good_orders.gid
		  WHERE good_orders.id=1
	*/
	var detail model.GoodOrder
	redis_key := "good_order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").
			Select(
				"good_orders.id as OrderId",
				"goods.good_code as GoodCode",
				"goods.good_name as GoodName",
				"good_orders.order_code as OrderCode",
				"good_orders.order_price as OrderPrice",
			).
			Joins("LEFT JOIN goods ON goods.id = good_orders.gid").
			Where("good_orders.id = ?", id).
			Debug().
			Find(&detail)
		
		jsonData, _ := json.Marshal(detail)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &detail)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": detail,
	})
}
